#region License
//-----------------------------------------------------------------------------
// Copyright (c) 2008, Aaron MacDougall, Daniel Jeffery
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Aaron MacDougall or Daniel Jeffery nor the names of its contributors may
//   be used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion

namespace Agro2D
{
    /// <summary>
    /// This is the real meat and veg. Plays texture animations that are split in frames.
    /// Each frame is specified by a sourceRectangle. 
    /// </summary>
    public class FrameAnimation : IAnimation
    {
        protected List<Rectangle> sourceRectangles;
        protected TextureReference texture;
        protected double fps;
        protected bool loop;
        protected int frameNum;
        protected uint dataFrameWidth;
        protected uint dataFrameHeight;
        protected uint dataNumframes;
        protected uint dataNumColumns;
        protected double countdown;

        /// <summary>
        /// Get the collection of SourceRectangles.
        /// </summary>
        public ICollection<Rectangle> SourceRectangles
        {
            get { return this.sourceRectangles; }
        }

        /// <summary>
        /// Get and set the source Texture for this animation.
        /// </summary>
        [ImportAttribute] 
        public TextureReference Texture
        {
            get { return this.texture; }
            set
            {
                Debug.Assert(value != null);
                this.texture = value;
            }
        }

        /// <summary>
        /// Get and set the frames per second that the animation is updated with.
        /// </summary>
        [ImportAttribute] 
        public double FPS
        {
            get { return this.fps; }
            set
            {
                Debug.Assert(value >= 0);
                this.fps = value;
            }
        }

        /// <summary>
        /// Get and set the loop variable. This indicates whether the animation
        /// should start playing from the beginning when ended.
        /// </summary>
        [ImportAttribute] 
        public bool Loop
        {
            get { return this.loop; }
            set { this.loop = value; }
        }

        // The following Properties are for the benefit of the Level editor.
        
        [ImportAttribute]
        public uint frameWidth
        {
            get { return this.dataFrameWidth; }
            set { this.dataFrameWidth = value; }
        }

        [ImportAttribute]
        public uint frameHeight
        {
            get { return this.dataFrameHeight; }
            set { this.dataFrameHeight = value; }
        }

        [ImportAttribute]
        public uint numframes
        {
            get { return this.dataNumframes; }
            set { this.dataNumframes = value; }
        }

        [ImportAttribute]
        public uint numColumns
        {
            get { return this.dataNumColumns; }
            set { this.dataNumColumns = value; }
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public FrameAnimation()
        {
            this.sourceRectangles = new List<Rectangle>();
            this.texture = null;
            this.fps = 5.0d;
            this.loop = true;
            this.frameNum = -1;
            this.countdown = 0.0f;
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="texture">source texture for the animation. Cannot be null.</param>
        /// <param name="fps">frames per second that the animation is updated with</param>
        /// <param name="loop">indicates whether the animation  should start playing 
        /// from the beginning when ended</param>
        public FrameAnimation(TextureReference texture, double fps, bool loop)
        {
            Debug.Assert(texture != null);
            Debug.Assert(fps > 0);

            this.sourceRectangles = new List<Rectangle>();
            this.texture = texture;
            this.fps = fps;
            this.loop = loop;
            this.frameNum = -1;
            this.countdown = 0.0f;
        }

        /// <summary>
        /// Generates this animations sourceRectangles (frames).
        /// </summary>
        /// <param name="texture">source texture for the animation. null</param>
        /// <param name="frameWidth">the width of each frame</param>
        /// <param name="frameHeight">the height of each frame</param>
        /// <param name="numFrames">the number of frames in the texture</param>
        /// <param name="numColumns">the number of columns in the animations texture</param>
        public virtual void GenerateSourceRectangles(TextureReference textureReference, uint frameWidth, uint frameHeight, uint numFrames, uint numColumns)
        {
            Texture2D texture = TextureManager.Instance.GetTexture(textureReference);

            Debug.Assert(frameWidth > 0);
            Debug.Assert(frameHeight > 0);
            Debug.Assert(numFrames > 0);
            Debug.Assert(numColumns > 0);
            Debug.Assert(numColumns * frameWidth <= texture.Width);
            Debug.Assert((numFrames / numColumns) * frameHeight <= texture.Height);

            this.texture = textureReference;

            uint x = 0;
            uint y = 0;
            int column = 0;
            for (int i = 0; i < numFrames; i++)
            {
                this.sourceRectangles.Add(new Rectangle((int)x, (int)y, (int)frameWidth, (int)frameHeight));

                x += frameWidth;
                column++;
                if (column == numColumns)
                {
                    x = 0;
                    column = 0;
                    y += frameHeight;
                }
            }
        }

        /// <summary>
        /// Sets the current frame in the animation.
        /// </summary>
        /// <param name="frameNum">desired frame</param>
        /// <param name="spriteProperties"></param>
        private void SetFrame(int frameNum, ref SpriteProperties spriteProperties)
        {
            Debug.Assert(frameNum >= 0);
            Debug.Assert(frameNum < this.sourceRectangles.Count);

            this.frameNum = frameNum;
            spriteProperties.SourceRectangle = this.sourceRectangles[frameNum];
            spriteProperties.Texture = this.texture;
        }

        /// <summary>
        /// Gets the current/active frame in the animation.
        /// </summary>
        public int CurrentFrame
        {
            get { return this.frameNum; }
            set { this.frameNum = value; }
        }

        /// <summary>
        /// Updates the current animation with the current gameTime so that it can play.
        /// </summary>
        /// <param name="gameTime">game time</param>
        /// <param name="spriteProperties">spriteProperties of the sprite whom the animation belongs</param>
        /// <returns>returns true if the animation has finished</returns>
        public override bool Animate(GameTime gameTime, SpriteProperties spriteProperties)
        {
            if (this.sourceRectangles.Count != 0)
            {
                // The first source rectangle is set on the first update
                if(spriteProperties.SourceRectangle.Width == 0 && spriteProperties.SourceRectangle.Height == 0)
                {
                    SetFrame(0, ref spriteProperties);
                    return true;
                }
                else
                {
                    this.countdown -= gameTime.ElapsedGameTime.TotalSeconds;

                    if(this.countdown <= 0.0d)
                    {
                        this.countdown = 0.0d;
                        this.countdown = 1.0d / this.fps;

                        this.frameNum++;
                        if(this.frameNum >= this.sourceRectangles.Count)
                        {
                            if(this.loop)
                                this.frameNum = 0;
                            else
                                return true;
                        }

                        SetFrame(this.frameNum, ref spriteProperties);
                    }
                }
            }               

            return false;
        }

        /// <summary>
        /// Returns a cloned version of this object.
        /// </summary>
        /// <returns>Cloned version of this object.</returns>
        public override object Clone()
        {
            FrameAnimation clonedAnimation = new FrameAnimation();
            clonedAnimation.fps = this.fps;
            clonedAnimation.loop = this.loop;
            clonedAnimation.texture = this.texture;

            clonedAnimation.frameHeight = this.frameHeight;
            clonedAnimation.frameWidth = this.frameWidth;
            clonedAnimation.numframes = this.numframes;
            clonedAnimation.numColumns = this.numColumns;

            foreach (Rectangle rect in this.sourceRectangles)
                clonedAnimation.sourceRectangles.Add(rect);

            return clonedAnimation;
        }
    }
}